﻿using System;
using OperationPlugins.Handlers;
using OperationPlugins.Reflections;

namespace OperationPlugins.Mvc.Filters
{
    /// <summary>
    /// Used to tell that the current action method should invoke plugins handlers, meaning <see cref="IHandler"/> implementations, 
    /// to handle its data.
    /// 
    /// To use this, apply this attribute to an action method.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class UseActionMethodHandlersAttribute : UseActionMethodHandlersForAllActionsAttribute
    {
        /// <summary>
        /// Initializes a new instance of the UseActionMethodHandlersAttribute class.
        /// </summary>
        /// <param name="moments">The moment when plugin handlers should be invoked.</param>
        public UseActionMethodHandlersAttribute(ActionMethodMoment moments) : base(moments)
        {
        }

        protected override void OnCurrentMoment()
        {
            // Prevent duplicate handling!
            foreach (var b in ActionExecutingContext.ActionDescriptor.ControllerDescriptor.ControllerType.GetAttributes<UseActionMethodHandlersForAllActionsAttribute>())
            {
                if ((b.Moments & CurrentMoment) == CurrentMoment)
                {
                    return;
                }
            }

            base.OnCurrentMoment();
        }

    }
}
